// pages/topic-location/topic-location.js
import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";

Page({
  data: {
    numberArray: [],//选项
    chooseNum: null,
    value:null,//选择的值
    isShowImg: true,//是否显示大图
    timeStr: 0,//页面倒计时
    count: 0,//题目数量
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    imageUrl: '', //第一张图
    questionImageUrl:'', //第二张图
    questionAnswer:null,//答案
    title:'',//标题
    questionIndex:0,//当前题型索引
    topicContent:[],//当前题型所有题目
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },

  onLoad() {
    this.getTopicData();

    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },

  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },

  async getCurrentTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {topicContent, currentIndex, count} = this.data;
    // 缓存下一题图片
    let newIndex = currentIndex + 1;
    if(newIndex < count){
      util.preLoadImg(questionIndex,newIndex)
    }

    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    const stemArray = JSON.parse(currentTopic.stem); // 得到第一张大图数组
    const content = stemArray[0].content;// 第一张大图数据
    const residenceTime = parseInt(stemArray[0].residenceTime, 10);
    const countdown = isNaN(residenceTime) ? 3000 : residenceTime;//第一张大图显示时间
    const questionContent = JSON.parse(currentTopic.answerSheet).content;// 第二张大图数据
    const questionCountdown = JSON.parse(currentTopic.answerSheet).residenceTime;
    const timeStr = parseInt(questionCountdown, 10) / 1000;//第二张图显示后题目停留时长
    const imgSrcMatch = content.match(/<img[^>]+src="([^">]+)"/);// 第一张大图
    // const questionImgSrc = questionContent.match(/<img[^>]+src="([^">]+)"/);// 第二张大图
    // const imageUrl = util.base_url + imgSrcMatch[1];// 拼接第一张大图
    const preImgs = wx.getStorageSync('preImgs')||[];
    let imageUrl = '';
    if (imgSrcMatch && imgSrcMatch[1]) {
      let imgSrc = imgSrcMatch[1];
      // 判断是否已经包含完整的 URL（http 或 https）
      if (imgSrc.startsWith('http')) {
        imageUrl = imgSrc;
      } else {
        imageUrl = util.base_url + imgSrc;
      }
    }

    const isIos =  util.checkPlatform()
    if(isIos){
      imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,jpg'
    }else{
      imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,webp'
    }
    // 替换缓存图片
    
    // const questionImageUrl = util.base_url + questionImgSrc[1];// 拼接第二张大图
    // 替换 img 标签的 src 为完整路径
    // const newContent = questionContent.replace(/<img[^>]+src="([^">]+)"/, function(match, src) {
    //    // 判断 src 是否包含 http 或 https
    //     if (src.startsWith('http')) {
    //       // 如果已经包含完整 URL，则不拼接 base_url
    //       return `<img class="question-img" src="${src}"`;
    //     } else {
    //       // 如果不包含，则拼接 base_url
    //       return `<img class="question-img" src="${util.base_url + src}"`;
    //     }
    // });

    const newContent = await util.replaceAsync(questionContent,/<img[^>]+src="([^">]+)"/,preImgs,(str)=>{
      return `<img class="question-img" src="${str}"`
    })

    const numberArray = currentTopic.optionList;//选项
    const questionAnswer = currentTopic.questionAnswer;//答案
    const descArray = JSON.parse(currentTopic.describe); // 得到标题数组
    const title = descArray[0].content;// 标题数据
    // 检查选项中的 content 是否为空，如果不为空则在 newContent 中添加显示
    let updatedContent = newContent;
    // numberArray.forEach((option, index) => {
    //   if (option.content && option.content.trim() !== '') {
    //     // 如果 content 不为空，则在 newContent 中添加显示内容的标签
    //     updatedContent += `<span style="display:block;margin: 10px;">${option.serialNumber}：${option.content}</span>`;
    //   }
    //   // 如果 fileUrl 不为空，则在 newContent 中添加显示内容的标签
    //   if (option.fileUrl && option.fileUrl.trim() !== '') {

    //     const originalFileUrl = option.fileUrl;
    //     // 判断 fileUrl 是否包含 http 或 https
    //     if (originalFileUrl.startsWith('http')) {
    //       // 如果已经包含完整 URL，则不拼接 base_url
    //       option.fileUrl = originalFileUrl;
    //     } else {
    //       // 如果不包含，则拼接 base_url
    //       option.fileUrl = util.base_url + originalFileUrl;
    //     }
    //     // 如果 fileUrl 不为空，则在 newContent 中添加显示内容的标签
    //     updatedContent += `<div style="display: inline-block;vertical-align: middle;"><div style="display:flex;align-items:flex-start;margin: 10px;">${option.serialNumber}：<img src="${option.fileUrl}" style="width:40px;height:40px;" /></div></div>`;
    //   }
    // });
    for (let index = 0; index < numberArray.length; index++) {
      const option = numberArray[index];
      if (option.content && option.content.trim() !== '') {
        updatedContent += `<span style="display:block;margin: 10px;">${option.serialNumber}：${option.content}</span>`;
      }
      if (option.fileUrl && option.fileUrl.trim() !== '') {
        const originalFileUrl = option.fileUrl;
        if (originalFileUrl.startsWith('http')) {
          option.fileUrl = originalFileUrl;
        } else {
          option.fileUrl = util.base_url + originalFileUrl;
        }
        let src2 =  preImgs.find(item => item.url===option.fileUrl)?.path??''
        option.fileUrl = src2||option.fileUrl
        let src = await util.pathToBase64(option.fileUrl,src2)
        updatedContent += `<div style="display: inline-block;vertical-align: middle;"><div style="display:flex;align-items:flex-start;margin: 10px;">${option.serialNumber}：<img src="${src}" style="width:40px;height:40px;" /></div></div>`;
      }
    }
    // 使用 wx.nextTick 确保视图更新完成后再开始倒计时
    this.setData({
      currentTopic,
      imageUrl,
      questionImageUrl:updatedContent,
      numberArray,
      questionAnswer,
      title,
      // 记录题目开始时间
      questionStartTime: new Date().getTime()
    }, () => {
      // 视图更新完成后的回调
      setTimeout(() => {
        this.setData({
          isShowImg: false,
          timeStr
        });
      }, countdown);
    });
  },

  onCountdownFinish() {
    // 倒计时结束，视为错误
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });

    const {currentIndex} = this.data;

    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(true);

    let totalCount = currentIndex + 1;
    this.setData({
      currentIndex: totalCount,
      answerRecords: newAnswerRecords
    })

    setTimeout(() => {
      const {count} = this.data;
      if (totalCount >= count) {
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);//跳转下一题
      } else {
        // 继续下一题
        this.getCurrentTopicData();
        this.setData({
          isShowImg: true,
          chooseNum: null,
          value:''
        })
      }
    }, 1000)
  },

  onChoose(e) {
    let index = e.currentTarget.dataset.index;
    let {numberArray} = this.data;
    let value = numberArray[index].serialNumber;
    this.setData({
      chooseNum: index,
      value
    })
  },

  // 提交
  onSubmit() {
    let {count, currentIndex, value} = this.data;
    if (!value) return;

    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value);

    let totalCount = currentIndex + 1;
    this.setData({
      currentIndex: totalCount,
      answerRecords: newAnswerRecords
    })

    if (totalCount >= count) {
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);//跳转下一题
    } else {
      // 继续下一题
      this.getCurrentTopicData();
      this.setData({
        isShowImg: true,
        chooseNum: null,
        value:''
      })
    }
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '') {
    const {currentIndex, questionStartTime, topicContent, questionAnswer} = this.data;

    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);

    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];

    // 判断是否正确（超时视为错误）
    let isRight = 0;
    let option = '';

    if (!isTimeout) {
      option = userOption;
      isRight = (userOption === questionAnswer) ? 1 : 0;
    }

    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: currentTopic.questionAnswer,
      score: 0,
    });

    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);

    return newAnswerRecords;
  },

  onUnload() {
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({
        countdownInterval: null
      });
    }
  }
});
